package org.spider.spiderweb.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spider.api.domain.vo.DatasourceVo;
import org.spider.api.domain.model.DataSourceModel;
import org.spider.api.domain.utilDomain.Result;
import org.spider.core.service.DatasourceService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Date;
import java.util.List;


@RestController
@RequestMapping("/datasource")
public class DataSourceController {
    @Resource
    private DatasourceService datasourceService;
    private static final Logger log = LoggerFactory.getLogger(DataSourceController.class);

    //====================================================增删改查===========================================
    //分页显示
    @GetMapping("/list")
    public Result getDatasourceList(@RequestParam(name = "page", defaultValue = "1") Integer page,
                                    @RequestParam(name = "limit", defaultValue = "1") Integer limit,
                                    @RequestParam(name = "name", defaultValue = "") String name) {
        IPage<DataSourceModel> iPage = datasourceService.selectPages(new Page<>(page, limit), name);

        return Result.getInstance(iPage);
    }

    @GetMapping("/all")
    public Result getDatasourceAll(){
        List<DatasourceVo> list = datasourceService.listAll();
        return Result.getInstance(list);
    }

    @GetMapping("/{id}")
    public Result selectById(@PathVariable Integer id) {
        if (id == null) return Result.getInstance(false);
        DataSourceModel model = datasourceService.getById(id);
        return Result.getInstance(model);
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        boolean flag = datasourceService.removeById(id);
        return Result.getInstance(flag);
    }

    @PutMapping
    public Result update(@RequestBody DataSourceModel dataSource) {
        if (dataSource == null) return Result.getInstance(0, "传入对象为null");
        log.info(dataSource.toString());
        boolean flag = datasourceService.updateById(dataSource);
        return Result.getInstance(flag);
    }

    @PostMapping
    public Result save(@RequestBody DataSourceModel dataSourceModel) {
        if (dataSourceModel == null) return Result.getInstance(false);
        dataSourceModel.setCreatDatetime(new Date());
        boolean saved = datasourceService.save(dataSourceModel);
        return Result.getInstance(saved);
    }

    @GetMapping("/tables")
    public Result listTables(@RequestParam("dsId") String dsId){
        return Result.getInstance(datasourceService.listTables(dsId));
    }

    @Deprecated
    @GetMapping("/tableDetails")
    public Result listTableDetails(@RequestParam("dsId") String dsId){
        return Result.getInstance(datasourceService.listTableDetails(dsId));
    }

    @GetMapping("/oneTableDetails")
    public Result oneTableDetails(@RequestParam("dsId")String dsId,
                                  @RequestParam("table") String table){
        return Result.getInstance(datasourceService.tableDetails(dsId,table));
    }

    //====================================================测试===========================================
    @PostMapping("/test")
    public Result test(@RequestBody DataSourceModel dataSource) {
        log.info("测试数据库连接:" + dataSource);
        if (StringUtils.isBlank(dataSource.getDriverClassName())) {
            return Result.getInstance(1, "DriverClassName不能为空");
        }
        if (StringUtils.isBlank(dataSource.getUrl())) {
            return Result.getInstance(1, "jdbcUrl不能为空");
        }
        String username = dataSource.getUsername();
        if (StringUtils.isBlank(username)) {
            return Result.getInstance(1, "用户名不能为空!");
        }
        String password = dataSource.getPassword();
        if (StringUtils.isBlank(password)) {
            return Result.getInstance(1, "密码不能为空!");
        }
        Connection connection = null;
        try {
            Class.forName(dataSource.getDriverClassName());
            String url = dataSource.getUrl();
            connection = DriverManager.getConnection(url, username, password);
            return Result.getInstance(1, "success");
        } catch (ClassNotFoundException e) {
            return Result.getInstance(1, "找不到驱动包:" + dataSource.getDriverClassName());
        } catch (Exception e) {
            return Result.getInstance(1, "连接失败" + e.getMessage());
        } finally {
            if (connection != null)
                try {
                    connection.close();
                } catch (Exception e) {
                }
        }
    }
}
